#include "button.hpp"

Button::~Button(){
    if(_task){
        _belong->RemoveTask(_task);
    }
}

void Button::CheckState(void* button){
    auto &r=((Button*)button)->_area;
    int x,y;
    SDL_GetMouseState(&x,&y);
    if(x<r.x||x>r.x+r.w||y<r.y||y>r.y+r.h){
        ((Button*)button)->_state=button_up;
        ((Button*)button)->_belong->RemoveTask(((Button*)button)->_task);
        ((Button*)button)->_task=NULL;
        SDL_SetCursor(arrow_cursor);
    }
}
void Button::Pop(void* button){
    ((Button*)button)->_state=0;
}

Font* Button::font(){return _font;}
const char* Button::text(){return _text;}
SDL_Color Button::text_color(){return _text_color;}

Button::Button(Window* window,SDL_Rect &rect,const char* text,
SDL_Color release,SDL_Color press,SDL_Color on,
SDL_Color text_color,Font* font):Control(window){
    _task=NULL;
    _area=rect;
    release_color=release;
    press_color=press;
    on_color=on;
    this->_text_color=text_color;
    this->_font=font;
    _state=0;
    this->_text=text;
    _t=window->renderer->RenderText(font,text,text_color);
}
Button::Button(Window* window):Control(window){
    _task=NULL;
    release_color=Color::Green;
    press_color=Color::Red;
    on_color=Color::Blue;
    _text_color=Color::Black;
    _font=default_font;
    _text="button";
    _t=window->renderer->RenderText(default_font,"button",Color::Black);
    _state=0;
}

void Button::SetText(const char* new_text,Font* font,SDL_Color color){
    SDL_DestroyTexture(_t);
    _t=_belong->renderer->RenderText(font,new_text,color);
    _text=new_text,_text_color=color,_font=font;
}

void Button::_press(int x,int y,int clicks,unsigned char key){}

void Button::_release(int x,int y,int clicks,unsigned char key){
    _state=button_down;
    _belong->AddTask(Pop,this,3);
    if(clicks==1){
        OnClick(x,y,key);
        return;
    }
    OnDoubleClick(x,y,key);
}
void Button::_mouse_move(int x,int y){
    if(!_state){
        _state=button_on;
    }
    if(!_task&&_enabled){
        _task=_belong->AddTask(CheckState,this,1,false,true);
    }
    if(_enabled){
        SDL_SetCursor(button_cursor);
    }
}
void Button::_draw(){
    Renderer* renderer=_belong->renderer;
    SDL_Rect r;
    auto x=_area.x,y=_area.y;
    r.x=x+5,r.y=y+5;
    SDL_QueryTexture(_t,NULL,NULL,&r.w,&r.h);
    if(!_enabled){
        renderer->SetColor(release_color);
        renderer->FillRect(_area);
        renderer->DrawTexture(NULL,&r,_t);
        return;
    }
    switch(_state){
        case button_down:
        renderer->SetColor(press_color);
        break;
        case button_up:
        renderer->SetColor(release_color);
        break;
        case button_on:
        renderer->SetColor(on_color);
        break;
    }
    renderer->FillRect(_area);
    renderer->DrawTexture(NULL,&r,_t);
}